7 * Class to represent an image
9 * Provides methods to retrieve paths (physical, logical, URL),
10 * to generate thumbnails or for uploading.
18 var $name, # name of the image
19 $imagePath, # Path of the image
21 $title, # Title object for this image. Initialized when needed.
22 $fileExists, # does the image file exist on disk?
23 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory
24 $historyLine, # Number of line to return by nextHistoryLine()
25 $historyRes, # result of the query for the image's history
28 $bits, # --- returned by getimagesize, see http://de3.php.net/manual/en/function.getimagesize.php
36 * Create an Image object from an image name
38 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
39 * @param bool $recache if true, ignores anything in memcached and sets the updated metadata
42 function Image( $name, $recache = false ) {
44 global $wgUseSharedUploads, $wgUseLatin1, $wgSharedLatin1, $wgLang, $wgMemc, $wgDBname,
45 $wgSharedUploadDBname;
48 $this->title
= Title
::makeTitleSafe( NS_IMAGE
, $this->name
);
49 $this->fromSharedDirectory
= false;
50 $this->imagePath
= $this->getFullPath();
52 $n = strrpos( $name, '.' );
53 $this->extension
= strtolower( $n ?
substr( $name, $n +
1 ) : '' );
55 $hashedName = md5($this->name
);
56 $cacheKey = "$wgDBname:Image:".$hashedName;
60 $cachedValues = $wgMemc->get( $cacheKey );
62 if (!empty($cachedValues) && is_array($cachedValues)) {
63 if ($wgUseSharedUploads && $cachedValues['fromShared']) {
64 # if this is shared file, we need to check if image
65 # in shared repository has not changed
66 $commonsCachedValues = $wgMemc->get( "$wgSharedUploadDBname:Image:".$hashedName );
67 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)) {
68 $this->name
= $commonsCachedValues['name'];
69 $this->imagePath
= $commonsCachedValues['imagePath'];
70 $this->fileExists
= $commonsCachedValues['fileExists'];
71 $this->fromSharedDirectory
= true;
72 $gis = $commonsCachedValues['gis'];
77 $this->name
= $cachedValues['name'];
78 $this->imagePath
= $cachedValues['imagePath'];
79 $this->fileExists
= $cachedValues['fileExists'];
80 $this->fromSharedDirectory
= false;
81 $gis = $cachedValues['gis'];
88 $this->fileExists
= file_exists( $this->imagePath
);
90 # If the file is not found, and a shared upload directory
91 # like the Wikimedia Commons is used, look for it there.
92 if (!$this->fileExists
&& $wgUseSharedUploads) {
94 # In case we're on a wgCapitalLinks=false wiki, we
95 # capitalize the first letter of the filename before
96 # looking it up in the shared repository.
97 $this->name
= $wgLang->ucfirst($name);
99 # Encode the filename if we're on a Latin1 wiki and the
100 # shared repository is UTF-8
101 if($wgUseLatin1 && !$wgSharedLatin1) {
102 $this->name
= utf8_encode($name);
105 $this->imagePath
= $this->getFullPath(true);
106 $this->fileExists
= file_exists( $this->imagePath
);
107 $this->fromSharedDirectory
= true;
111 if ( $this->fileExists
) {
112 # Don't try to get the size of sound and video files, that's bad for performance
113 if ( !Image
::isKnownImageExtension( $this->extension
) ) {
115 } elseif( $this->extension
== 'svg' ) {
116 wfSuppressWarnings();
117 $gis = getSVGsize( $this->imagePath
);
120 wfSuppressWarnings();
121 $gis = getimagesize( $this->imagePath
);
126 $cachedValues = array('name' => $this->name
,
127 'imagePath' => $this->imagePath
,
128 'fileExists' => $this->fileExists
,
129 'fromShared' => $this->fromSharedDirectory
,
132 $wgMemc->set( $cacheKey, $cachedValues );
134 if ($wgUseSharedUploads && $this->fromSharedDirectory
) {
135 $cachedValues['fromShared'] = false;
136 $wgMemc->set( "$wgSharedUploadDBname:Image:".$hashedName, $cachedValues );
140 if( $gis !== false ) {
141 $this->width
= $gis[0];
142 $this->height
= $gis[1];
143 $this->type
= $gis[2];
144 $this->attr
= $gis[3];
145 if ( isset( $gis['bits'] ) ) {
146 $this->bits
= $gis['bits'];
152 if($this->fileExists
) {
153 $this->url
= $this->wfImageUrl( $this->name
, $this->fromSharedDirectory
);
157 $this->historyLine
= 0;
161 * Remove image metadata from cache if any
163 * Don't call this, use the $recache parameter of Image::Image() instead
165 * @param string $name the title of an image
168 function invalidateMetadataCache( $name ) {
169 global $wgMemc, $wgDBname;
170 $wgMemc->delete("$wgDBname:Image:".md5($name));
176 * Create a new image object from a title object.
178 * @param Title $nt Title object. Must be from namespace "image"
181 function newFromTitle( $nt ) {
182 $img = new Image( $nt->getDBKey() );
188 * Return the name of this image
196 * Return the associated title object
199 function getTitle() {
204 * Return the URL of the image file
211 function getViewURL() {
212 if( $this->mustRender() ) {
213 return $this->createThumb( $this->getWidth() );
215 return $this->getURL();
220 * Return the image path of the image in the
221 * local file system as an absolute path
224 function getImagePath()
226 return $this->imagePath
;
230 * Return the width of the image
232 * Returns -1 if the file specified is not a known image type
235 function getWidth() {
240 * Return the height of the image
242 * Returns -1 if the file specified is not a known image type
245 function getHeight() {
246 return $this->height
;
250 * Return the size of the image file, in bytes
254 $st = stat( $this->getImagePath() );
263 * Return the type of the image
276 * Return the escapeLocalURL of this image
279 function getEscapeLocalURL() {
280 return $this->title
->escapeLocalURL();
284 * Return the escapeFullURL of this image
287 function getEscapeFullURL() {
288 return $this->title
->escapeFullURL();
292 * Return the URL of an image, provided its name.
294 * @param string $name Name of the image, without the leading "Image:"
295 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
298 function wfImageUrl( $name, $fromSharedDirectory = false ) {
299 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
300 if($fromSharedDirectory) {
302 $path = $wgSharedUploadPath;
304 $base = $wgUploadBaseUrl;
305 $path = $wgUploadPath;
307 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
308 return wfUrlencode( $url );
312 * Returns true iff the image file exists on disk.
317 return $this->fileExists
;
324 function thumbUrl( $width, $subdir='thumb') {
325 global $wgUploadPath, $wgUploadBaseUrl,
326 $wgSharedUploadPath,$wgSharedUploadDirectory,
327 $wgUseLatin1,$wgSharedLatin1;
328 $name = $this->thumbName( $width );
329 if($this->fromSharedDirectory
) {
331 $path = $wgSharedUploadPath;
332 if($wgUseLatin1 && !$wgSharedLatin1) {
333 $name=utf8_encode($name);
336 $base = $wgUploadBaseUrl;
337 $path = $wgUploadPath;
339 $url = "{$base}{$path}/{$subdir}" .
340 wfGetHashPath($name, $this->fromSharedDirectory
)
342 return wfUrlencode($url);
346 * Return the file name of a thumbnail of the specified width
348 * @param integer $width Width of the thumbnail image
349 * @param boolean $shared Does the thumbnail come from the shared repository?
352 function thumbName( $width, $shared=false ) {
353 global $wgUseLatin1,$wgSharedLatin1;
354 $thumb = $width."px-".$this->name
;
355 if( $this->extension
== 'svg' ) {
356 # Rasterize SVG vector images to PNG
359 if( $shared && $wgUseLatin1 && !$wgSharedLatin1) {
360 $thumb=utf8_encode($thumb);
366 * Create a thumbnail of the image having the specified width/height.
367 * The thumbnail will not be created if the width is larger than the
368 * image's width. Let the browser do the scaling in this case.
369 * The thumbnail is stored on disk and is only computed if the thumbnail
370 * file does not exist OR if it is older than the image.
373 * Keeps aspect ratio of original image. If both width and height are
374 * specified, the generated image will be no bigger than width x height,
375 * and will also have correct aspect ratio.
377 * @param integer $width maximum width of the generated thumbnail
378 * @param integer $height maximum height of the image (optional)
381 function createThumb( $width, $height=-1 ) {
382 $thumb = $this->getThumbnail( $width, $height );
383 if( is_null( $thumb ) ) return '';
384 return $thumb->getUrl();
388 * As createThumb, but returns a ThumbnailImage object. This can
389 * provide access to the actual file, the real size of the thumb,
390 * and can produce a convenient <img> tag for you.
392 * @param integer $width maximum width of the generated thumbnail
393 * @param integer $height maximum height of the image (optional)
394 * @return ThumbnailImage
397 function &getThumbnail( $width, $height=-1 ) {
398 if ( $height == -1 ) {
399 return $this->renderThumb( $width );
401 if ( $width < $this->width
) {
402 $thumbheight = $this->height
* $width / $this->width
;
403 $thumbwidth = $width;
405 $thumbheight = $this->height
;
406 $thumbwidth = $this->width
;
408 if ( $thumbheight > $height ) {
409 $thumbwidth = $thumbwidth * $height / $thumbheight;
410 $thumbheight = $height;
412 $thumb = $this->renderThumb( $thumbwidth );
413 if( is_null( $thumb ) ) {
414 $thumb = $this->iconThumb();
420 * @return ThumbnailImage
422 function iconThumb() {
423 global $wgStylePath, $wgStyleDirectory;
425 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
426 foreach( $try as $icon ) {
427 $path = '/common/images/' . $icon;
428 $filepath = $wgStyleDirectory . $path;
429 if( file_exists( $filepath ) ) {
430 return new ThumbnailImage( $filepath, $wgStylePath . $path );
437 * Create a thumbnail of the image having the specified width.
438 * The thumbnail will not be created if the width is larger than the
439 * image's width. Let the browser do the scaling in this case.
440 * The thumbnail is stored on disk and is only computed if the thumbnail
441 * file does not exist OR if it is older than the image.
442 * Returns an object which can return the pathname, URL, and physical
443 * pixel size of the thumbnail -- or null on failure.
445 * @return ThumbnailImage
448 function /* private */ renderThumb( $width ) {
449 global $wgImageMagickConvertCommand;
450 global $wgUseImageMagick;
451 global $wgUseSquid, $wgInternalServer;
453 $width = IntVal( $width );
455 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
456 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).'/'.$thumbName;
457 $thumbUrl = $this->thumbUrl( $width );
458 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
459 if ( ! $this->exists() )
461 # If there is no image, there will be no thumbnail
465 # Sanity check $width
471 if( $width > $this->width
&& !$this->mustRender() ) {
472 # Don't make an image bigger than the source
473 return new ThumbnailImage( $this->getImagePath(), $this->getViewURL() );
476 if ( (! file_exists( $thumbPath ) ) ||
( filemtime($thumbPath) < filemtime($this->imagePath
) ) ) {
477 if( $this->extension
== 'svg' ) {
478 global $wgSVGConverters, $wgSVGConverter;
479 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
480 global $wgSVGConverterPath;
482 array( '$path/', '$width', '$input', '$output' ),
483 array( $wgSVGConverterPath,
485 escapeshellarg( $this->imagePath
),
486 escapeshellarg( $thumbPath ) ),
487 $wgSVGConverters[$wgSVGConverter] );
488 $conv = shell_exec( $cmd );
492 } elseif ( $wgUseImageMagick ) {
494 # Specify white background color, will be used for transparent images
495 # in Internet Explorer/Windows instead of default black.
496 $cmd = $wgImageMagickConvertCommand .
497 " -quality 85 -background white -geometry {$width} ".
498 escapeshellarg($this->imagePath
) . " " .
499 escapeshellarg($thumbPath);
500 $conv = shell_exec( $cmd );
502 # Use PHP's builtin GD library functions.
504 # First find out what kind of file this is, and select the correct
505 # input routine for this.
509 switch( $this->type
) {
511 $src_image = imagecreatefromgif( $this->imagePath
);
514 $src_image = imagecreatefromjpeg( $this->imagePath
);
518 $src_image = imagecreatefrompng( $this->imagePath
);
519 $truecolor = ( $this->bits
> 8 );
521 case 15: # WBMP for WML
522 $src_image = imagecreatefromwbmp( $this->imagePath
);
525 $src_image = imagecreatefromxbm( $this->imagePath
);
528 return 'Image type not supported';
531 $height = floor( $this->height
* ( $width/$this->width
) );
533 $dst_image = imagecreatetruecolor( $width, $height );
535 $dst_image = imagecreate( $width, $height );
537 imagecopyresampled( $dst_image, $src_image,
539 $width, $height, $this->width
, $this->height
);
540 switch( $this->type
) {
545 #$thumbUrl .= ".png";
546 #$thumbPath .= ".png";
547 imagepng( $dst_image, $thumbPath );
550 #$thumbUrl .= ".jpg";
551 #$thumbPath .= ".jpg";
552 imageinterlace( $dst_image );
553 imagejpeg( $dst_image, $thumbPath, 95 );
558 imagedestroy( $dst_image );
559 imagedestroy( $src_image );
562 # Check for zero-sized thumbnails. Those can be generated when
563 # no disk space is available or some other error occurs
565 if( file_exists( $thumbPath ) ) {
566 $thumbstat = stat( $thumbPath );
567 if( $thumbstat['size'] == 0 ) {
568 unlink( $thumbPath );
573 # This has to be done after the image is updated and present for all machines on NFS,
574 # or else the old version might be stored into the squid again
577 $wgInternalServer.$thumbUrl
579 wfPurgeSquidServers($urlArr);
582 return new ThumbnailImage( $thumbPath, $thumbUrl );
583 } // END OF function createThumb
586 * Return the image history of this image, line by line.
587 * starts with current version, then old versions.
588 * uses $this->historyLine to check which line to return:
589 * 0 return line for current version
590 * 1 query for old versions, return first one
591 * 2, ... return next old version from above query
595 function nextHistoryLine() {
596 $fname = 'Image::nextHistoryLine()';
597 $dbr =& wfGetDB( DB_SLAVE
);
598 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
599 $this->historyRes
= $dbr->select( 'image',
600 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
601 array( 'img_name' => $this->title
->getDBkey() ),
604 if ( 0 == wfNumRows( $this->historyRes
) ) {
607 } else if ( $this->historyLine
== 1 ) {
608 $this->historyRes
= $dbr->select( 'oldimage',
609 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
610 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
611 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
614 $this->historyLine ++
;
616 return $dbr->fetchObject( $this->historyRes
);
620 * Reset the history pointer to the first element of the history
623 function resetHistory() {
624 $this->historyLine
= 0;
628 * Return true if the file is of a type that can't be directly
629 * rendered by typical browsers and needs to be re-rasterized.
632 function mustRender() {
633 return ( $this->extension
== 'svg' );
637 * Return the full filesystem path to the file. Note that this does
638 * not mean that a file actually exists under that location.
640 * This path depends on whether directory hashing is active or not,
641 * i.e. whether the images are all found in the same directory,
642 * or in hashed paths like /images/3/3c.
645 * @param boolean $fromSharedDirectory Return the path to the file
646 * in a shared repository (see $wgUseSharedRepository and related
647 * options in DefaultSettings.php) instead of a local one.
650 function getFullPath( $fromSharedRepository = false ) {
651 global $wgUploadDirectory, $wgSharedUploadDirectory;
652 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
654 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
657 $fullpath = $dir . wfGetHashPath($name, $fromSharedRepository) . $name;
665 function isKnownImageExtension( $ext ) {
666 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
667 return in_array( $ext, $extensions );
674 * Returns the image directory of an image
675 * If the directory does not exist, it is created.
676 * The result is an absolute path.
678 * @param string $fname file name of the image file
681 function wfImageDir( $fname ) {
682 global $wgUploadDirectory, $wgHashedUploadDirectory;
684 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
686 $hash = md5( $fname );
687 $oldumask = umask(0);
688 $dest = $wgUploadDirectory . '/' . $hash{0};
689 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
690 $dest .= '/' . substr( $hash, 0, 2 );
691 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
698 * Returns the image directory of an image's thubnail
699 * If the directory does not exist, it is created.
700 * The result is an absolute path.
702 * @param string $fname file name of the thumbnail file, including file size prefix
703 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
704 * @param boolean $shared (optional) use the shared upload directory
707 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false) {
708 return wfImageArchiveDir( $fname, $subdir, $shared );
712 * Returns the image directory of an image's old version
713 * If the directory does not exist, it is created.
714 * The result is an absolute path.
716 * @param string $fname file name of the thumbnail file, including file size prefix
717 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
718 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
721 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
722 global $wgUploadDirectory, $wgHashedUploadDirectory,
723 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
724 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
725 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
726 if (!$hashdir) { return $dir.'/'.$subdir; }
727 $hash = md5( $fname );
728 $oldumask = umask(0);
729 # Suppress warning messages here; if the file itself can't
730 # be written we'll worry about it then.
731 $archive = $dir.'/'.$subdir;
732 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
733 $archive .= '/' . $hash{0};
734 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
735 $archive .= '/' . substr( $hash, 0, 2 );
736 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
744 * Return the hash path component of an image path (URL or filesystem),
745 * e.g. "/3/3c/", or just "/" if hashing is not used.
747 * @param $dbkey The filesystem / database name of the file
748 * @param $fromSharedDirectory Use the shared file repository? It may
749 * use different hash settings from the local one.
751 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
752 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
753 global $wgHashedUploadDirectory;
755 $ishashed = $fromSharedDirectory ?
$wgHashedSharedUploadDirectory :
756 $wgHashedUploadDirectory;
759 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
767 * Record an image upload in the upload log.
769 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = '', $source = '' ) {
770 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
771 global $wgUseCopyrightUpload;
773 $fname = 'wfRecordUpload';
774 $dbw =& wfGetDB( DB_MASTER
);
776 # img_name must be unique
777 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
778 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
782 $now = wfTimestampNow();
783 $size = IntVal( $size );
785 if ( $wgUseCopyrightUpload ) {
786 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
787 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
788 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
790 else $textdesc = $desc ;
792 $now = wfTimestampNow();
794 # Test to see if the row exists using INSERT IGNORE
795 # This avoids race conditions by locking the row until the commit, and also
796 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
797 $dbw->insert( 'image',
801 'img_timestamp' => $dbw->timestamp($now),
802 'img_description' => $desc,
803 'img_user' => $wgUser->getID(),
804 'img_user_text' => $wgUser->getName(),
807 $descTitle = Title
::makeTitleSafe( NS_IMAGE
, $name );
809 if ( $dbw->affectedRows() ) {
810 # Successfully inserted, this is a new image
811 $id = $descTitle->getArticleID();
814 $article = new Article( $descTitle );
815 $article->insertNewArticle( $textdesc, $desc, false, false, true );
818 # Collision, this is an update of an image
819 # Get current image row for update
820 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
821 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
823 # Insert it into oldimage
824 $dbw->insert( 'oldimage',
826 'oi_name' => $s->img_name
,
827 'oi_archive_name' => $oldver,
828 'oi_size' => $s->img_size
,
829 'oi_timestamp' => $dbw->timestamp($s->img_timestamp
),
830 'oi_description' => $s->img_description
,
831 'oi_user' => $s->img_user
,
832 'oi_user_text' => $s->img_user_text
836 # Update the current image row
837 $dbw->update( 'image',
840 'img_timestamp' => $dbw->timestamp(),
841 'img_user' => $wgUser->getID(),
842 'img_user_text' => $wgUser->getName(),
843 'img_description' => $desc,
844 ), array( /* WHERE */
849 # Invalidate the cache for the description page
850 $descTitle->invalidateCache();
853 $log = new LogPage( 'upload' );
854 $log->addEntry( 'upload', $descTitle, $desc );
858 * Returns the image URL of an image's old version
860 * @param string $fname file name of the image file
861 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
864 function wfImageArchiveUrl( $name, $subdir='archive' ) {
865 global $wgUploadPath, $wgHashedUploadDirectory;
867 if ($wgHashedUploadDirectory) {
868 $hash = md5( substr( $name, 15) );
869 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
870 substr( $hash, 0, 2 ) . '/'.$name;
872 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
874 return wfUrlencode($url);
878 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
879 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
881 * @param string $length
882 * @return int Length in pixels
884 function scaleSVGUnit( $length ) {
885 static $unitLength = array(
892 '' => 1.0, // "User units" pixels by default
893 '%' => 2.0, // Fake it!
895 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
896 $length = FloatVal( $matches[1] );
898 return round( $length * $unitLength[$unit] );
901 return round( FloatVal( $length ) );
906 * Compatible with PHP getimagesize()
907 * @todo support gzipped SVGZ
908 * @todo check XML more carefully
909 * @todo sensible defaults
911 * @param string $filename
914 function getSVGsize( $filename ) {
918 // Read a chunk of the file
919 $f = fopen( $filename, "rt" );
920 if( !$f ) return false;
921 $chunk = fread( $f, 4096 );
924 // Uber-crappy hack! Run through a real XML parser.
925 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
929 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
930 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
932 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
933 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
936 return array( $width, $height, 'SVG',
937 "width=\"$width\" height=\"$height\"" );
942 * Wrapper class for thumbnail images
945 class ThumbnailImage
{
947 * @param string $path Filesystem path to the thumb
948 * @param string $url URL path to the thumb
951 function ThumbnailImage( $path, $url ) {
954 $size = @getimagesize
( $this->path
);
956 $this->width
= $size[0];
957 $this->height
= $size[1];
965 * @return string The thumbnail URL
972 * Return HTML <img ... /> tag for the thumbnail, will include
973 * width and height attributes and a blank alt text (as required).
975 * You can set or override additional attributes by passing an
976 * associative array of name => data pairs. The data will be escaped
977 * for HTML output, so should be in plaintext.
979 * @param array $attribs
983 function toHtml( $attribs = array() ) {
984 $attribs['src'] = $this->url
;
985 $attribs['width'] = $this->width
;
986 $attribs['height'] = $this->height
;
987 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
990 foreach( $attribs as $name => $data ) {
991 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
998 * Return the size of the thumbnail file, in bytes or false if the file
1002 function getSize() {
1003 $st = stat( $this->path
);